package com.zlkj.pro.modular.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.enums.StatusEnum;
import cn.stylefeng.roses.kernel.rule.enums.YesOrNotEnum;
import cn.stylefeng.roses.kernel.rule.pojo.dict.SimpleDict;
import cn.stylefeng.roses.kernel.system.api.pojo.user.request.SysUserRequest;
import cn.stylefeng.roses.kernel.system.modular.role.entity.SysRole;
import cn.stylefeng.roses.kernel.system.modular.role.service.SysRoleService;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlkj.pro.core.consts.ProjectConstants;
import com.zlkj.pro.core.exception.BusinessException;
import com.zlkj.pro.core.util.ConvertUtil;
import com.zlkj.pro.modular.admin.entity.User;
import com.zlkj.pro.modular.admin.mapper.UserMapper;
import com.zlkj.pro.modular.admin.model.dto.UserDTO;
import com.zlkj.pro.modular.admin.model.vo.UserVO;
import com.zlkj.pro.modular.business.service.WebUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

import static com.zlkj.pro.core.consts.ProjectConstants.ROLE_ID_BMSH_MANAGER;
import static com.zlkj.pro.core.exception.enums.BusinessExceptionEnum.BUSINESS_EXCEPTION;

/**
 * @author liyang
 * @date 2024/4/6
 * @time 14:34
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class WebUserServiceImpl extends ServiceImpl<UserMapper, User> implements WebUserService {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysUserService sysUserService;


    @Override
    public Object dropDown() {
        List<SimpleDict> dictList = CollectionUtil.newArrayList();
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询正常状态
        queryWrapper.eq(SysRole::getStatusFlag, StatusEnum.ENABLE.getCode()).eq(SysRole::getDelFlag, YesOrNotEnum.N.getCode());
        sysRoleService.list(queryWrapper).forEach(sysRole -> {
            SimpleDict simpleDict = new SimpleDict();
            simpleDict.setId(sysRole.getRoleId());
            simpleDict.setCode(sysRole.getRoleCode());
            simpleDict.setName(sysRole.getRoleName());
            dictList.add(simpleDict);
        });
        return dictList;
    }

    @Override
    public PageResult<UserVO> findPage(UserDTO dto) {

        Integer pageNo = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        dto.setUserId(LoginContext.me().getLoginUser().getUserId());
        List<UserVO> list = userMapper.findPage(dto);
        Long total = userMapper.findPageCount(dto);
        return PageResultFactory.createPageResult(list, total, pageSize, pageNo);
    }

    @Override
    public boolean addUser(UserDTO dto) {
        // 根据手机号查询用户账号
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhone, dto.getPhone());
        queryWrapper.eq(User::getDelFlag, "N");
        List<User> userList = super.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "手机号已经注册！");
        }
        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(User::getAccount, dto.getAccount());
        queryWrapper2.eq(User::getDelFlag, "N");
        List<User> userList2 = super.list(queryWrapper2);
        if (CollectionUtils.isNotEmpty(userList2)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "账号已经注册！");
        }

        // 创建账号
        SysUserRequest sysUserRequest = ConvertUtil.turn(dto, SysUserRequest.class);
        sysUserRequest.setUserId(IdUtil.getSnowflake().nextId());
        sysUserRequest.setNickName(sysUserRequest.getRealName());
        sysUserRequest.setBirthday("2020-01-01");
        sysUserRequest.setSex("M");
        sysUserRequest.setEmail(" ");
        sysUserRequest.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserRequest.setPositionId(ProjectConstants.DEFAULT_POSITION_ID);//默认职位
        sysUserRequest.setStatusFlag(1);
        sysUserRequest.setOrgId(ProjectConstants.DEFAULT_ORG_ID);//默认添加到总公司下面
        sysUserRequest.setGrantOrgIdList(Collections.singletonList(ProjectConstants.DEFAULT_ORG_ID));
        sysUserService.add(sysUserRequest);

        // 补充代理商信息
        User user = new User();
        user.setUserId(sysUserRequest.getUserId());
        user.setStatusFlag(1);//启用
        user.setRegion(dto.getRegion());//设置用户地域
        super.updateById(user);

        // 授权角色
        SysUserRequest request = new SysUserRequest();
        request.setUserId(sysUserRequest.getUserId());
        request.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserService.grantRole(request);
        return true;
    }

    @Override
    public boolean editUser(UserDTO dto) {
        // 清空地域
        if (dto.getRoleId() != null && dto.getRoleId().equals(ROLE_ID_BMSH_MANAGER)){
            dto.setRegion("");
        }

        // 根据手机号查询用户账号
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getPhone, dto.getPhone());
        queryWrapper.eq(User::getDelFlag, "N");
        queryWrapper.ne(User::getUserId, dto.getUserId());
        List<User> userList = super.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(userList)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "手机号已经注册！");
        }

        LambdaQueryWrapper<User> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.eq(User::getAccount, dto.getAccount());
        queryWrapper2.eq(User::getDelFlag, "N");
        queryWrapper2.ne(User::getUserId, dto.getUserId());
        List<User> userList2 = super.list(queryWrapper2);
        if (CollectionUtils.isNotEmpty(userList2)) {
            throw new BusinessException(BUSINESS_EXCEPTION, "账号已经注册！");
        }

        User entity = ConvertUtil.turn(dto, User.class);
        SysUserRequest request = new SysUserRequest();
        request.setUserId(dto.getUserId());
        request.setGrantRoleIdList(Collections.singletonList(dto.getRoleId()));
        sysUserService.grantRole(request);
        return super.updateById(entity);
    }

}
